import { AxiosRequestConfig } from 'axios';
import { useUserStoreWithOut } from '/@/store/modules/user';
import { CreateAxiosOptions } from './axiosTransform';
const requestQueue = new Set();
let isLocked = false;

function addToQueue(config: AxiosRequestConfig, resolve: Fn, options: CreateAxiosOptions) {
  const userStore = useUserStoreWithOut();
  requestQueue.add(() => {
    const authorization = options.authenticationScheme
      ? `${options.authenticationScheme} ${userStore.getAccessToken}`
      : userStore.getAccessToken;
    if (config.headers) {
      config.headers.Authorization = authorization;
    } else {
      config.headers = { Authorization: authorization };
    }
    resolve(config);
  });
}

function clearQueue() {
  requestQueue.forEach((cb: Fn) => {
    cb();
  });
  requestQueue.clear();
}

async function refreshToken(config: AxiosRequestConfig, resolve: Fn, options: CreateAxiosOptions) {
  if (isLocked) return; // token被锁定，直接返回
  isLocked = true;
  const userStore = useUserStoreWithOut();
  await userStore.refreshToken();
  isLocked = false;
  addToQueue(config, resolve, options);
  clearQueue();
}

export function getConfigWithToken(
  config: AxiosRequestConfig,
  options: CreateAxiosOptions,
): AxiosRequestConfig | Promise<any> {
  return new Promise((resolve) => {
    if (isLocked) {
      addToQueue(config, resolve, options);
    } else {
      refreshToken(config, resolve, options);
    }
  });
}
